package com.shaozi.nc.mq.quartz;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Component;

import com.shaozi.data.mq.business.base.MqQuartzBean;
import com.shaozi.data.mq.business.quartz.QuartzApiHelper;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.MqApiQuartzModel;
import com.shaozi.nc.manage.secretary.SecretaryApiQuartzManage;
import com.shaozi.utils.common.BeanUtils;

@Component
public class QuartzApiHelperImpl implements QuartzApiHelper {

	public QuartzApiHelperImpl() {
	}

	@Override
	public MqQuartzBean getQuartzBean(JobDetail jobDetail) throws SzException {
		String _id = jobDetail.getJobDataMap().getString("_id");
		String companyId = jobDetail.getJobDataMap().getString("companyId");
		SecretaryApiQuartzManage quartzMgr = BeanUtils.getBean(SecretaryApiQuartzManage.class);
		MqApiQuartzModel quartzModel = quartzMgr.getModel(companyId, _id);
		if (quartzModel == null || quartzModel.getIsDel() != 0) {
			return null;
		}
		return QuartzBeanModelUtil.modelToBean(quartzModel);
	}

	@Override
	public void afterQuartz(JobExecutionContext context, MqQuartzBean quartzBean, boolean isSucc) throws SzException {
		SecretaryApiQuartzManage quartzMgr = BeanUtils.getBean(SecretaryApiQuartzManage.class);
		quartzMgr.logSchedule(quartzBean.getCompanyId(), quartzBean, isSucc ? 1 : 0, "");
		if (context.getNextFireTime() == null) {
			quartzMgr.delModel(quartzBean.getCompanyId(), quartzBean.getId(), MqApiQuartzModel.DelType_Finish);
		}
	}

}
